<script setup lang='tsx'>
import type { OptionsType, PlusColumn } from 'plus-pro-components'

import {
    useGetApplyDetail,
    useGetCategory,
    useGetEnterpriseBrandOptions,
    useGetProvinceCityCounty,
    useGetSupplieByTypeOptions,
    useUpdateApplyStatus,
} from '@fl/api/supplier'
import FlUpload from '@fl/components/fl-upload.vue'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { jsonToArray } from '@fl/utils/fn'
import { cascaderValueToString } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'
import { h } from 'vue'

const historyId = defineModel<string>('historyId', { required: true })
const historyVisible = defineModel<boolean>('historyVisible', { required: true })

const initialState = {
    authTime: [],
    brandId: [],
    catId: [],
    fileList: [],
    oldAuthTime: [],
    oldBrandId: [],
    oldCatId: [],
    oldFileList: [],
    oldRegion: [],
    region: [],
    remark: '',
    type: 1,
} as any
const state = ref(cloneDeep(initialState))

const isEdit = computed(() => !!historyId.value)
const getEnterpriseBrandParams = computed<string>(() => state.value.supplierId)
const getSupplierOptionsParams = computed(() => {
    return {
        type: 8,
        visible: unref(historyVisible),
    }
})

const { data: enterpriseBrandData } = useGetEnterpriseBrandOptions(getEnterpriseBrandParams)
const { data: categoryData, isLoading: isGetCategoryLoading } = useGetCategory()
const { isPending, mutate: updateApplyStatus } = useUpdateApplyStatus()
const { data: provinceCityCountyData } = useGetProvinceCityCounty()
const { data: supplierOptionsData, isLoading: isGetSupplierOptionsLoading } = useGetSupplieByTypeOptions(getSupplierOptionsParams)

const { data: applyDetailData, isLoading: isGetApplyDetailLoading } = useGetApplyDetail(historyId)

const formRef = ref()
const isFormLoading = computed(() => {
    return isGetApplyDetailLoading.value || isGetCategoryLoading.value || isGetSupplierOptionsLoading.value
})
const isSubmitLoading = computed(() => {
    return isPending.value
})
const brandOptions = computed(() => state.value.supplierId ? (enterpriseBrandData.value || []) : [])

const columns: PlusColumn[] = [
    {
        fieldProps: {
            disabled: isEdit.value,
        },
        label: '供应商',
        options: supplierOptionsData as OptionsType,
        prop: 'supplierId',
        valueType: 'select',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            disabled: isEdit.value,
            onChange: (value: string[][]) => {
                state.value.catName = cascaderValueToString(value, {
                    treeData: categoryData.value,
                })
            },
            props: { multiple: true },
        },
        options: categoryData as OptionsType,
        prop: 'oldCatId',
        renderLabel: () =>
            h(
                'span',
                {
                    style: {
                        color: arraysEqual(state.value.catId, state.value.oldCatId) ? '' : 'blue',
                    },
                },
                '原授权品类',
            ),
        valueType: 'cascader',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            disabled: isEdit.value,
            onChange: (value: string[][]) => {
                state.value.catName = cascaderValueToString(value, {
                    treeData: categoryData.value,
                })
            },
            props: { multiple: true },
        },
        options: categoryData as OptionsType,
        prop: 'catId',
        renderLabel: () =>
            h(
                'span',
                {
                    style: {
                        color: arraysEqual(state.value.catId, state.value.oldCatId) ? '' : 'red',
                    },
                },
                '现授权品类',
            ),
        valueType: 'cascader',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            disabled: isEdit.value,
            multiple: true,
            onChange: (value: string[]) => {
                state.value.brandName = value.map((item: string) => brandOptions.value.find((option: any) => option.value === item)!.label)
                    .join(',')
            },
        },
        options: brandOptions,
        prop: 'oldBrandId',
        renderLabel: () =>
            h(
                'span',
                {
                    style: {
                        color: arraysEqual(state.value.brandId, state.value.oldBrandId) ? '' : 'blue',
                    },
                },
                '原代理品牌',
            ),
        valueType: 'select',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            disabled: isEdit.value,
            multiple: true,
            onChange: (value: string[]) => {
                state.value.oldBrandId = value.map((item: string) => brandOptions.value.find((option: any) => option.value === item)!.label)
                    .join(',')
            },
        },
        options: brandOptions,
        prop: 'brandId',
        renderLabel: () =>
            h(
                'span',
                {
                    style: {
                        color: arraysEqual(state.value.brandId, state.value.oldBrandId) ? '' : 'red',
                    },
                },
                '现代理品牌',
            ),
        valueType: 'select',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            disabled: isEdit.value,
            endPlaceholder: '请选择结束时间',
            startPlaceholder: '请选择开始时间',
            type: 'daterange',
            valueFormat: 'YYYY-MM-DD',
        },
        prop: 'oldAuthTime',
        renderLabel: () =>
            h(
                'span',
                {
                    style: {
                        color: arraysEqual(state.value.authTime, state.value.oldAuthTime) ? '' : 'blue',
                    },
                },
                '原授权时间',
            ),
        valueType: 'date-picker',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            disabled: isEdit.value,
            endPlaceholder: '请选择结束时间',
            startPlaceholder: '请选择开始时间',
            type: 'daterange',
            valueFormat: 'YYYY-MM-DD',
        },
        prop: 'authTime',
        renderLabel: () =>
            h(
                'span',
                {
                    style: {
                        color: arraysEqual(state.value.authTime, state.value.oldAuthTime) ? '' : 'red',
                    },
                },
                '现授权时间',
            ),
        valueType: 'date-picker',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            disabled: isEdit.value,
        },
        options: provinceCityCountyData as OptionsType,
        prop: 'oldRegion',
        renderLabel: () =>
            h(
                'span',
                {
                    style: {
                        color: arraysEqual(state.value.region, state.value.oldRegion) ? '' : 'blue',
                    },
                },
                '原授权地区',
            ),
        valueType: 'cascader',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            disabled: isEdit.value,
        },
        options: provinceCityCountyData as OptionsType,
        prop: 'region',
        renderLabel: () =>
            h(
                'span',
                {
                    style: {
                        color: arraysEqual(state.value.region, state.value.oldRegion) ? '' : 'red',
                    },
                },
                '现授权地区',
            ),
        valueType: 'cascader',
    },
    {
        fieldProps: {
            disabled: isEdit.value,
        },
        prop: 'oldFileList',
        renderLabel: () =>
            h(
                'span',
                {
                    style: {
                        color: arraysEqual(state.value.fileList, state.value.oldFileList) ? '' : 'blue',
                    },
                },
                '原厂家授权函',
            ),
    },
    {
        fieldProps: {
            disabled: isEdit.value,
        },
        prop: 'fileList',
        renderLabel: () =>
            h(
                'span',
                {
                    style: {
                        color: arraysEqual(state.value.fileList, state.value.oldFileList) ? '' : 'red',
                    },
                },
                '现厂家授权函',
            ),
    },
    {
        label: '审核处理',
        options: [
            {
                label: '同意申请',
                value: 1,
            },
            {
                label: '拒绝申请',
                value: 2,
            },
        ],
        prop: 'type',
        valueType: 'radio',
    },
    {
        fieldProps: {
            autosize: { maxRows: 4, minRows: 2 },
        },
        hideInForm: computed(() => state.value.type !== 2),
        label: '拒绝理由',
        prop: 'remark',
        valueType: 'textarea',
    },
]

const rules = {
    authTime: [
        {
            message: '请选择授权时间',
            required: true,
            trigger: 'change',
        },
    ],
    brandId: [
        {
            message: '请选择代理品牌',
            required: true,
            trigger: 'change',
        },
    ],
    catId: [
        {
            message: '请选择授权品类',
            required: true,
            trigger: 'change',
        },
    ],
    fileList: [
        {
            message: '请上传厂家授权函',
            required: true,
            trigger: 'change',
        },
    ],
    oldAuthTime: [
        {
            message: '请选择授权时间',
            required: true,
            trigger: 'change',
        },
    ],
    oldBrandId: [
        {
            message: '请选择代理品牌',
            required: true,
            trigger: 'change',
        },
    ],
    oldCatId: [
        {
            message: '请选择授权品类',
            required: true,
            trigger: 'change',
        },
    ],
    oldFileList: [
        {
            message: '请上传厂家授权函',
            required: true,
            trigger: 'change',
        },
    ],
    oldRegion: [
        {
            message: '请选择授权地区',
            required: true,
            trigger: 'change',
        },
    ],
    region: [
        {
            message: '请选择授权地区',
            required: true,
            trigger: 'change',
        },
    ],
    remark: [
        {
            message: '请输入拒绝理由',
            required: true,
            trigger: 'change',
        },
    ],
    supplierId: [
        {
            message: '请选择供应商',
            required: true,
            trigger: 'change',
        },
    ],
    type: [
        {
            message: '请选择审核处理',
            required: true,
            trigger: 'change',
        },
    ],
}

async function onSubmitBtnClick() {
    const valid = await formRef.value.formInstance.validate()
    if (!valid)
        return
    submit()
}

function submit() {
    const { remark, type } = state.value
    updateApplyStatus({ id: historyId.value, remark, type }, {
        onSuccess() {
            ElMessage.success('操作成功')
            historyVisible.value = false
        },
    })
}

function onCancelBtnClick() {
    closed()
}

function arraysEqual(array1, array2) {
    if (!array1 && !array2) {
        return false
    }
    return JSON.stringify(array1) === JSON.stringify(array2)
    // if (!Array.isArray(array1) || !Array.isArray(array2)) {
    //     return false
    // }

    // if (array1.length !== array2.length) {
    //     return false
    // }

    // const flag = array1.every((item, index) => {
    //     const otherItem = array2[index]
    //     if (Array.isArray(item) && Array.isArray(otherItem)) {
    //         return arraysEqual(item, otherItem)
    //     }
    //     console.log(item, otherItem, 389)
    //     return item === otherItem
    // })
    // console.log(flag, 391)
    // return flag
}

function closed() {
    historyVisible.value = false
    historyId.value = ''
}

watch(() => state.value.supplierId, (newValue, oldValue) => {
    if (oldValue || !newValue) {
        state.value.brandId = []
    }
})

watchEffect(() => {
    if (isEdit.value && applyDetailData.value) {
        const data = cloneDeep(applyDetailData.value)
        const fileList = jsonToArray(data.file)
        const oldFileList = jsonToArray(data.oldFile)
        Object.assign(state.value, data, {
            authTime: [data.startTime, data.endTime],
            brandId: data.brandId && JSON.parse(data.brandId),
            catId: data.catId && JSON.parse(data.catId),
            fileList,
            oldAuthTime: [data.oldStartTime, data.oldEndTime],
            oldBrandId: data.oldBrandId && JSON.parse(data.oldBrandId),
            oldCatId: data.oldCatId && JSON.parse(data.oldCatId),
            oldFileList,
            oldRegion: data.oldRegion && JSON.parse(data.oldRegion),
            region: data.region && JSON.parse(data.region),
        })
    }
})
</script>

<template>
    <PlusDialog v-model="historyVisible"
                title="修改供应商关联"
                width="800"
                close-on-press-escape
                @closed="closed"
    >
        <el-skeleton v-if="isFormLoading"
                     animated
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="120"
                  :rules="rules"
                  :row-props="{ gutter: 10 }"
                  :has-footer="false"
        >
            <template #plus-field-fileList>
                <FlUpload v-model="state.fileList"
                          tips
                          :disabled="isEdit"
                          accept=".docx,.pdf,.jpg,.jpeg,.png"
                          list-type="text"
                />
            </template>

            <template #plus-field-oldFileList>
                <FlUpload v-model="state.oldFileList"
                          tips
                          :disabled="isEdit"
                          accept=".docx,.pdf,.jpg,.jpeg,.png"
                          list-type="text"
                />
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="onCancelBtnClick">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isSubmitLoading"
                           @click="onSubmitBtnClick"
                >
                    确定
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
